package com.xb.xbpm.controller;

import com.xb.xbpm.service.ISiteService;
import com.xb.xbpm.utils.EsUtils;
import com.xb.xbpm.utils.Tools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * 首页趋势分析
 * 从es获取数据
 * @Author gxd
 * @Date： 2018/7/23
 */
@Controller
@RequestMapping(value = "home")
public class HomeController {

    @Autowired
    EsUtils esUtils;
    @Autowired
    ISiteService siteService;


    @RequestMapping("/getTotalList")
    public @ResponseBody
    Map<String, Object> getTotalList(HttpServletRequest request){
        ModelMap map=new ModelMap();


        List<Map<String, Object>> pvList=new ArrayList<Map<String,Object>>();
        List<Map<String, Object>> uvList=new ArrayList<Map<String,Object>>();
        List<Map<String, Object>> ipList=new ArrayList<Map<String,Object>>();
        //新独立访客
        List<Map<String, Object>> ovList=new ArrayList<Map<String,Object>>();


        List<String> datelist=null;


        String startDate="";
        String endDate="";
        String siteid= request.getParameter("siteid");
        String date= request.getParameter("date");
        String userid= request.getParameter("userid");

        if(Tools.isEmpty(siteid)){
            List<Map<String,Object>> list1= new ArrayList<Map<String,Object>>();
            list1=siteService.getSiteList(userid);
            if(list1.size()>0){
                siteid=list1.get(0).get("id").toString();
            }else{
                map.put("pvList",pvList);
                map.put("uvList",uvList);
                map.put("ipList",ipList);
                map.put("ovList",ovList);//新增独立访客
                return map;
            }
        }

        if(Tools.notEmpty(date)){//日期不为空
            String [] strs=date.split(",");
            startDate=strs[0];
            endDate=strs[1];
        }else{//默认当天
            startDate=Tools.date2Str(new Date(),"yyyyMMdd");
        }

        try {
            //拼接索引
            String index="";
            if(Tools.isEmpty(endDate) || startDate.equals(endDate)){
                //一天的
                index="xblog_"+userid+"_"+startDate.replaceAll("-","");
            }else{
                //时间段内的所有索引值
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date start=null;
                Date end=null;

                start = format1.parse(startDate);
                end= format1.parse(endDate);
                datelist= getBetweenDates(start,end);
                //datelist.add(startDate.replace("-",""));
                datelist.add(endDate.replace("-",""));

                for (String s: datelist ) {
                    index+="xblog_"+userid+"_"+s+",";
                }

            }




            //索引暂时写死
            //index="xblog_lm1_20180807";
            //siteid="090909";



            //新增独立访客= (今天+历史 7天)的独立访客数  - 今天的uuid去重+昨天的uuid去重 -昨天的ip去重
            //获取今天以前7天的索引



            //1天 查询时间点 小时  时间段查询日期
            if(Tools.notEmpty(endDate) && !endDate.equals(startDate)){
                //时间段——日
                for (String s: datelist ) {
                    long pvnum=esUtils.getTotalCountPv("xblog_"+userid+"_"+s,siteid);
                    long uvnum=esUtils.getTotalCountUv("xblog_"+userid+"_"+s,siteid);
                    long ipnum=esUtils.getTotalCountIp("xblog_"+userid+"_"+s,siteid);
                    //新增独立访客list
                    String ovindexNoTheDate=getBeforDateIndex7(Tools.str2Date(s,"yyyyMMdd"),userid);//不包括当日
                    long ovnum1=esUtils.getTotalCountUv(ovindexNoTheDate,siteid);
                    String allIndex=ovindexNoTheDate+"xblog_"+userid+"_"+s;
                    long ovnum2=esUtils.getTotalCountUv(allIndex,siteid);
                    long ovnum=ovnum2-ovnum1;
                    if(ovnum<0){//避免出现负数
                        ovnum=0;
                    }
                    Map<String,Object> map1 = new HashMap<>();
                    Map<String,Object> map2 = new HashMap<>();
                    Map<String,Object> map3 = new HashMap<>();
                    Map<String,Object> map4 = new HashMap<>();//新增独立访客

                    String src=insertStringInParticularPosition(s.substring(4,8),"-",2);
                    map1.put("day",src);//返回 格式"08-01,1000" 20180807
                    map1.put("count",pvnum);
                    map2.put("count",uvnum);
                    map3.put("count",ipnum);
                    map4.put("count",ovnum);
                    pvList.add(map1);
                    uvList.add(map2);
                    ipList.add(map3);
                    ovList.add(map4);
                }

            }else{
                //时间段——小时
                //如果是今天设置时间节点 如果是之前的一天 查询24个节点
                int time=24;
                if(Tools.date2Str(new Date(),"yyyyMMdd").equals(startDate)){
                    time=Integer.valueOf(Tools.date2Str(new Date(),"HH"));//当前时间19:00取19
                }

                pvList=esUtils.getPvByTimeNode(index,"doc",siteid,time);
                uvList=esUtils.getUvByTimeNode(index,"doc",siteid,time);
                ipList=esUtils.getIpByTimeNode(index,"doc",siteid,time);


                String index2=getBeforDateIndex7(new Date(),userid);//不包括今天
                String todayIndex="xblog_"+userid+"_"+Tools.date2Str(new Date(),"yyyyMMdd");
                String index3=index2+todayIndex;
                long r2=esUtils.getTotalCountUv(index2,siteid);//不包括今天的
                //新增独立访客  目前采取和前一天比较
                ovList=esUtils.getOvByTimeNode(index3,"doc",siteid,time,r2);//分时间段小时 r2:历史去重uuid 总数 index3含今天的索引集合 然后根据时间筛选今天的

            }

        }catch (Exception e){
            e.getStackTrace();
        }


        map.put("pvList",pvList);
        map.put("uvList",uvList);
        map.put("ipList",ipList);
        map.put("ovList",ovList);//新增独立访客
        return map;
    }


    /**
     * 获取pvuvip值
     */
    @RequestMapping("/getTotalCount")
    public @ResponseBody
    Map<String, Object> getTotalCount(HttpServletRequest request){
        ModelMap map=new ModelMap();
        long pv=0;
        long uv=0;
        long ov=0;//新增独立
        long ip=0;
        double pc=0;//人均浏览页数

        List<String> datelist=null;

        String startDate="";
        String endDate="";
        String siteid= request.getParameter("siteid");
        String date= request.getParameter("date");
        String userid= request.getParameter("userid");

        if(Tools.isEmpty(siteid)){
            List<Map<String,Object>> list1= new ArrayList<Map<String,Object>>();
            list1=siteService.getSiteList(userid);
            if(list1.size()>0){
                siteid=list1.get(0).get("id").toString();
            }else{
                map.put("pv",pv);
                map.put("uv",uv);
                map.put("ov",ov);
                map.put("ip",ip);
                return map;
            }
        }

        if(Tools.notEmpty(date)){//日期不为空
            String [] strs=date.split(",");
            startDate=strs[0];
            endDate=strs[1];
        }else{//默认当天
            startDate=Tools.date2Str(new Date(),"yyyyMMdd");
        }

        try {
            //拼接索引
            String index="";
            if(Tools.isEmpty(endDate) || startDate.equals(endDate)){
                //一天的
                index="xblog_"+userid+"_"+startDate.replaceAll("-","");
            }else{
                //时间段内的所有索引值
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date start=null;
                Date end=null;

                start = format1.parse(startDate);
                end= format1.parse(endDate);
                datelist= getBetweenDates(start,end);
                //datelist.add(startDate.replace("-",""));
                datelist.add(endDate.replace("-",""));

                for (String s: datelist ) {
                    index+="xblog_"+userid+"_"+s+",";
                }

            }

            pv=esUtils.getTotalCountPv(index,siteid);
            //浏览量为0  其余全是0 直接返回
            if(pv<=0){
                map.put("pv",pv);
                map.put("uv",uv);
                map.put("ov",ov);
                map.put("ip",ip);
                map.put("pc",pc);
                return map;
            }

            uv=esUtils.getTotalCountUv(index,siteid);//uid去重
            ip=esUtils.getTotalCountIp(index,siteid);//ip去重
            if(uv>0){
                pc=pv/uv;//pv/uv
            }

            //新增独立访客= (今天+历史 7天)的独立访客数  - 今天的uuid去重+昨天的uuid去重 -昨天的ip去重
            //获取今天以前7天的索引
            String index2=getBeforDateIndex7(new Date(),userid);//不包括今天

            String todayIndex="xblog_"+userid+"_"+Tools.date2Str(new Date(),"yyyyMMdd");

            String index3=index2+todayIndex;


            long r1=esUtils.getTotalCountUv(index3,siteid);//包括今天的
            long r2=esUtils.getTotalCountUv(index2,siteid);//不包括今天的
            ov=r1-r2;
        }catch (Exception e){
            e.getStackTrace();
        }
        map.put("pv",pv);
        map.put("uv",uv);
        map.put("ov",ov);
        map.put("ip",ip);
        map.put("pc",pc);

        return map;
    }

    /**
     * 获取两个日期之间的日期
     * @param start 开始日期
     * @param end 结束日期
     * @return 日期集合
     */
    private static List<String> getBetweenDates(Date start, Date end) {
        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        List<String> result = new ArrayList<String>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        //tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            result.add(format1.format(tempStart.getTime()));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }

    /**
     * 获取7天前的索引
     * @return
     */
    private  String getBeforDateIndex7(Date end,String userid) {

        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String indexs="";
        List<String> result = new ArrayList<String>();
        Calendar tempStart = Calendar.getInstance();
        //Date end=new Date();
        Date start=null;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        start = calendar.getTime();

        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            indexs+="xblog_"+userid+"_"+format1.format(tempStart.getTime())+",";
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return indexs;
    }

    /**
     * 在指定位置插入字符
     * @param src
     * @param dec
     * @param position
     * @return
     */
    private String insertStringInParticularPosition(String src, String dec, int position){
        StringBuffer stringBuffer = new StringBuffer(src);
        return stringBuffer.insert(position, dec).toString();
    }

    /*public static void main(String[] args) {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date start=null;
        Date end=null;
        try {
            start = format1.parse("2018-07-02");
            end= format1.parse("2018-07-20");

        } catch (ParseException e) {
            e.printStackTrace();
        }
       List<String> list=HomeController.getBetweenDates(start,end);

        for (String s: list) {
            System.out.println(s);
        }


    }*/


    public static void main(String[] args) {

        String url="http://url.xinkuai.com/897/8244";

        String lyid=url.substring(url.lastIndexOf("/")+1);

        System.out.println(lyid);

        LocalDate day = LocalDate.now().minusDays(1);
        System.out.println(day);

        System.out.println(6%3);
        Double d=0.02;

        Double m=2.04;

        m=m-(m*d);
        System.out.println(m);

            Date date=new Date();

            Instant instant = date.toInstant();

            ZoneId zoneId  = ZoneId.systemDefault();

            LocalDate dd= instant.atZone(zoneId).toLocalDate();
            System.out.println(dd);


        String adsInfo=new String(Base64.getDecoder().decode("aj0wJm09MCZmPTAmcj0mdT1odHRwJTNBJTJGJTJGbG9jYWxob3N0JTJGdGVzdC5odG1sJnJlcz0zNzV4NjY3JnQ9JUU2JUI1JThCJUU4JUFGJTk1JUU1JUI5JUJGJUU1JTkxJThBJmw9emgtQ04mYz0xJmg9NDImc2U9MiZmcD1mOGZjOWZlZiZwZj1XaW4zMiZ0cz10cnVlfHRydWV8MSZ4a2d5cz1Hb29nbGUgSW5jLiZ4a3hycT1BTkdMRSAoSW50ZWwoUikgVUhEIEdyYXBoaWNzIDYyMCBEaXJlY3QzRDExIHZzXzVfMCBwc181XzApJnB2bnVtPTM0Jmp3PXNjcmlwdF9pZnJhbWUmY2FsY19jcGNfY3BhX2NwbV8yXzQwMF8yMDA9NyZzdmlzaXQ9MCZ6dmlzaXQ9MCZ4Yl91dWlkPTYxZTQwMTA3NDVkNTQ0MDQ5YjQ2MTEwNjk3ODYxZjg2JnhiX3N1aWQ9"));
        adsInfo=StringUtils.substringBefore(adsInfo, ";");

        String [] strs=adsInfo.split("&");
        String [] strs2="j=0".split("=");
        System.out.println(strs[0]+"_"+strs[1]+"_"+strs[2]+"_"+strs[3]);


        /*String r=Tools.getRandomNum(2);

        System.out.println(r);

        String res="";
        BigDecimal a=new BigDecimal(100);
        BigDecimal b=new BigDecimal(5);

        b=b.pow(2);
       b= new BigDecimal(Math.sqrt(45));
       b=b.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(b);*/


        double f=(double) 3/21;

        BigDecimal bg = new BigDecimal(f);
        Double f1 = bg.setScale(2,RoundingMode.HALF_UP).doubleValue();

        System.out.println(f1);
        /*try {

            String timenode=Tools.date2Str(new Date(),"yyyy-MM-dd");
            timenode+=" 0:59:59";



            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;

            date = simpleDateFormat.parse(timenode);

            long ts = date.getTime();
            res = String.valueOf(ts);
            System.out.println(res);
        } catch (ParseException e) {
            e.printStackTrace();
        }*/


    }


}
